<?php
defined('_VALID_MOS') or die('Direct Access to this location is not allowed.');

define('MAILMAN2_BASEPATH_COMPONENTS', dirname(__FILE__));
define('MAILMAN2_BASEPATH_ADMINISTRATOR', dirname(__FILE__).'/../../administrator/components/com_mailman2');

if(file_exists(MAILMAN2_BASEPATH_ADMINISTRATOR .'/language/'.$mosConfig_lang.'.php'))
include_once(MAILMAN2_BASEPATH_ADMINISTRATOR .'/language/'.$mosConfig_lang.'.php');
else include_once(MAILMAN2_BASEPATH_ADMINISTRATOR .'/language/english.php');

//Load the joomla code
require_once( 'includes/joomla.php' );

//Get the information from the joomla user
$my = $mainframe->getUser();
$g_email = $my->email;

//Loading configuration
$database->setQuery("SELECT * FROM #__mailman2 WHERE id='1'");
if(!$database->query()) {
	mailman2_sql_error($database->getErrorMsg());
	return false;
}

$rows = $database->loadObjectList();

$row = $rows[0];

$g_maildomain = $row->maildomain;
$g_domain = $row->domainname;
$g_protocol = $row->protocol;
$g_appended_domain = $row->appdomain;
$g_sitename = $row->sitename;
$g_adminpw = $row->adminpw;
$g_sender = $row->sender;
$g_external_lists = $row->extlist;
$g_debug = $row->debug;
$g_admin_dir = $row->admindir;
$g_communitybuilder = $row->communitybuilder;
$g_communitybuilderstring = $row->communitybuilderstring;

//This section checks to see if the default values are still in the config
//If so, the user hasn't configured it.
$notconfigured = 0 ;

if ( $g_appended_domain == '_my-domain.com' ) { $notconfigured = 1; }
if ( $g_domain == 'my-domain.com' ) { $notconfigured = 1; }
if ( $g_sitename == 'My Website' )  { $notconfigured = 1; }
if ( $g_adminpw == 'adminpw' ) { $notconfigured = 1; }
if ( $g_sender == 'noreply@domain.com' ) { $notconfigured = 1; }

if ( $notconfigured == 1 ) {
	echo "
<br><br><br><br><br><br>
<b>Warning! This component has not been configured yet.
<br>You need to configure the com_mailman component via its admin screen in Joomla!
<br>Go to your Joomla! admin console & select Components -> com_mailman2 and
change the default values
</b>";
exit;
}

//This section only pertains to the external mailing lists
//section.  Most users will not use this.

if ($g_external_lists == 1) {

	//Get the user's "real name"
	$g_name = $my->name;

	//Massage the name so it's only two words
	$g_name = preg_replace( "/\s+/", '%20', $g_name, 1 );
	$g_name = preg_replace( "/\s+/", '_', $g_name );

	//If it came out to only one word, add LASTNAME
	if (! preg_match("/%20/", "$g_name") ) {
		$g_name = $g_name . '%20' . 'YOURLASTNAME' ;
	}
} else {
	$g_name = "NOEXTERNAL";
}

//End external section
//(On to mailman)

//Compose the header for confirmation emails!
$email_message = _MM_EMAIL_HEAD1. $g_sitename . _MM_EMAIL_HEAD2;

//Get task value.
//This tells us if it's the first time we're called, or if we're doing something

$task = mosGetParam( $_GET, 'task' );

$g_userinformation = getUserDescription($g_communitybuilder, $g_communitybuilderstring);
$g_fulluserinformation = $g_userinformation . " <" . $g_email . ">";

// set admin url
$g_admin_url = $g_protocol . $g_domain . $g_admin_dir ;

//If we're displaying the form
if ($task == "") {

	//Show the initial page, passing it the domain, appended domain,
	//the email address of the user (g_email), the user's real name (g_name),
	//the intro message (g_intromessage), the adminpw, site name, sender, and debug flag
	
	show_initial_page($g_admin_url,$g_appended_domain,$g_email,$g_name,$g_adminpw,$g_sitename,$g_sender,$g_debug);

} elseif (strcmp($task , "subscribe") == 0) {

	process_requests($g_email,$g_fulluserinformation,$g_maildomain,$g_appended_domain,$g_sitename,$g_admin_url,$g_adminpw,$g_sender,$g_debug);

}

function parseString($data, $formalstring) {
	// data is an object or an associative array, with key as databse name. 
	// things between @@ are field names in database.
	// thigs between ## must be printed only if all things between @@ are not null
	// $formalstring is the source string to be converted
	
	// if the data are an object, convert it to associative array.
	if(is_object($data)) $data = get_object_vars($data);
	
	// look for conditional strings
	$countmatched = preg_match_all('/#[^#]+#/', $formalstring, $conditionalmatched, PREG_SET_ORDER);
	// check if there is at least one conditional
	if($countmatched > 0) {
		// conditional foreach, run the cicle.
		foreach($conditionalmatched[0] as $match) {
			// get out the ## things
			$matchunquoted = preg_replace("/#([^#]+)#/", "$1", $match);
			// replace vars in string with proper values.
			$matchreplaced = parseString($data, $matchunquoted);
			// replace vars in string with null values.
			$emptystring = preg_replace("/@[^@]*@/", "", $matchunquoted);
			
			// if the two strings are the same, the field is not set.
			if($emptystring == $matchreplaced)
				$formalstring =  str_replace("$match", "", $formalstring);
			else $formalstring = str_replace("$match", "$matchreplaced", $formalstring);
		}
	}
	
	// look for vars
	preg_match_all('/@[^@]+@/', $formalstring, $matched);
	foreach($matched[0] as $match) {
		// strip out @ things, that are the first and the last char.
		$key = str_replace("@", "", $match);
		// replace the @...@ thing with value from array
		$formalstring = str_replace("$match", "$data[$key]", $formalstring);
	}
	// return modified string.
	return $formalstring;
}

function getUserDescription($l_communitybuilder, $l_communitybuilderstring) {
	global $my;
	global $user;
	global $database;
	global $_CB_framework; 
	
	//print_r($_CB_framework);
	
	// debug
	//print "<div><pre>" . print_r($my) . "</pre></div>";
	
	if($l_communitybuilder == 1) {
		$query="SELECT * FROM #__comprofiler WHERE `user_id` = '" . $my->id . "';";
		$database->setQuery( $query );
		$user_cb_data = $database->loadObjectList();
		// we have unique id, so count must be 1.
		if(count($user_cb_data) != 1) {
			echo "Error: returned row != 1";
			exit(1);
		}
		$l_userdescription = parseString($user_cb_data[0], $l_communitybuilderstring);
	}
	else $l_userdescription = $my->name;
		
	return $l_userdescription;
}

function arrayToString($array) {
	// reset value
	$string = null;
	
	// is it an array?
	if(is_array($array)) {
		// extract array values
		foreach($array as $value)
			// is an array $value?
			if(is_array($value))
				// recursive call
				$string .= arrayToString($value);
			else {
				// The End Of The Line, concatenate strings
				$string .= $value;
			}
	}
	else $string .= $array;
	// this is always a concatenation of strings
	return $string;
}
	


function extract_form($string) {
	// variables
	$result = null;
	//print "<pre>" . print_r($string) . "</pre>";
	
	// first of all let's get a unique string
	$string = arrayToString($string);
	// debug
	//print "<pre>Is arrayToString working?\n" . htmlentities($string) . "</pre>";
	 
	//get all input lines 
	//preg_match_all('/<INPUT.*>/', $string, $inputs);
	$inputs = preg_split("/<input/i", $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
	//print "<pre>" . print_r($inputs) . "</pre>";
	
	
	foreach($inputs as $line) {
		preg_match_all('/name=".*"/', $line, $name);
		preg_match_all('/value=".*"/', $line, $value);
			
		for($i=0; $i<count($name[0]); $i++) {
			preg_match('/name="([^"]+)"/', $name[0][$i], $sname);
			$sname = $sname[1];
			
			preg_match('/value="([^"]+)"/', $value[0][$i], $svalue);
			$svalue = $svalue[1];
			
			$result[$sname] = $svalue; 
		}
	}
	return $result;
}


function curl_post($url='',$data=array(),$opt=array()) {
	# create cURL resource
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	$output = curl_exec($ch);
	curl_close($ch);
	return $output;
}

function show_initial_page($l_admin_url,$l_appended_domain, $l_email, $l_name, $l_adminpw, $l_sitename,$l_sender,$l_debug) {
	
	// this will match both new and old mailman style
	// look also for $findmbr
	$le_email=urlencode($l_email);
	if ( $l_debug == 1 ) {
		print '<pre>$l_email: ' . $l_email . '</pre>';
		print '<pre>$le_email: ' . $le_email . '</pre>';
	}
	
	echo _MM_FRONTEND_TITLE;

	if ( $l_debug == 1 ) {
		echo "<br><blink><b>Your are in debug mode!  <br>Several emails will be sent to your registered email address: " . $l_email . "" .
				"<br>To turn off debug mode, set Debug to No in the admin screen of this component.</blink></b><br>" ;
	}

	//Begin Non-mailman section
	//I put this here to also support helping people to subscribe to
	//external lists.  If you want to do this, you have to edit this part of the script yourself.
	//To not display this section, tell com_mailman to not use external lists.

	if ($l_name != "NOEXTERNAL" ) {
	echo "
<h3>External Mailing Lists</h3>
<p>
These mailing lists are hosted by other sites, but each one is also
connected to one of our forums.  Follow the links below to subscribe to them.
</p>

<table>
<tr>
<td width=#275>
<a href=\"mailto:veritas-bu-request@mailman.eng.auburn.edu?subject=subscribe&body=subscribe\">Subscribe to the NetBackup Mailing List</a>
</td>
<td>(Just click Send) </td> </tr>
<tr> <td>
<a href=\"mailto:listserv@listserv.temple.edu?subject=subscribe&body=SUBSCRIBE%20NETWORKER%20$l_name\">Subscribe to the NetWorker Mailing List</a>
</td><td>
(Body should be \"SUBSCRIBE NETWORKER FIRSTNAME LASTNAME\")
</td> </tr>
<tr> <td>
<a href=\"mailto:listserv@vm.marist.edu?subject=Subscribe&body=SUBSCRIBE%20ADSM-L%20$l_name\">Subscribe to the TSM Mailing List</a>
</td><td>
(Body should be \"SUBSCRIBE ADSM-L FIRSTNAME LASTNAME\")
</td></tr></table>
	";
	}

	//End Non-mailman section

	echo "<h3>$l_sitename</h3>";
	echo _MM_HOSTED_INTRO1, $l_sitename, _MM_HOSTED_INTRO2, $l_email, _MM_HOSTED_INTRO3;

	//Start the form
	echo "<form action='index.php?option=com_mailman2&task=subscribe' method='post'>";
	$radio_counter=0;

	//Start the table
	echo "<table>" ;
	echo  "<tr><td width=#150><h4><b>" . _MM_HOSTED_MAILLIST . "</b></h4></td><td><b><h4>" . _MM_HOSTED_MAILLIST_DESC . "<h4></b></td><td><b><h4>Status</h4></b></td></tr>";

	//Now we're going to build a list of mailing lists that they can
	//subscribe to.  For each list, we check to see if they're subscribed
	//If they are, we activate the appropriate radio button

	//First Run the mailman command to list lists and store it in $content
	//Create the command

	$adminurl=$l_admin_url;
	$content=@file_get_contents("$adminurl","FALSE");

	if ( $l_debug == 1 ) {
		$my_content = "Using this command:\n" . $adminurl . "\nI saw this:\n" . $content ;
		$subject = "Listing mailing lists";
		mail($l_email, $subject, $my_content, "From:$l_sender");
	}

	//This should fail if the admin URL is wrong, as it should not see this line
	//<td><a href="http://<domain>/mailman/admin/LISTNAME"><strong>

	if ( preg_match("/a href=.*strong.*strong/", "$content") ) {

		//Content is now some HTML code only a few lines of which we need
		$listarray = preg_split('/\n/',$content);

		//let's loop through it and look for lines that look like this:
		//<td><a href="http://<domain>/mailman/admin/LISTNAME"><strong>
		//<td>Description Text Goes Here</td>

		$table="off";

		foreach ($listarray as $element) {

			global $lists ;

			if ( preg_match("/a href=.*strong.*strong/", "$element") ) { $table="on"; }

			if ( "$table" == "on" ) {
					if ( preg_match("/a href=.*strong.*strong/", "$element") ) {
					$listname = preg_replace("/.*href=./","","$element") ;
					$listname = preg_replace("/.>.*/","","$listname") ;
					$listname = preg_replace("/.*\//","","$listname") ;
				} elseif ( preg_match("/<td>.*<.td>/", "$element") ) {
					$description = preg_replace("/.*<td>/","","$element") ;
					$description = preg_replace("/<.td>.*/","","$description") ;
					$description = preg_replace("/<\/*em>/","","$description") ;
					$lists["$listname"] = "$description";
				}
			}

			if ( preg_match("/<.table>/", "$element") ) { $table="off";}
		}
	} else {

		$my_content = "Using this command:\n" . $adminurl . "\nI saw this:\n" . $content ;
		$subject = "Listing mailing lists";
		mail($l_email, $subject, $content, "From:$l_sender");

		echo "
<br><br><br><br><br><br>
<b>You do not appear to have the correct URL for administering Mailman.
<br>The supplied URL was: $adminurl
<br>Please check the value you specified for the domain in the configuration screen of this component.
<br>An email has been sent to you with a screen shot of what the component saw at this phase.
</b>";
exit;
	}

	//For each mailing list in the list
	foreach ($lists as $short_list_full => $short_description) {

		//Create the short list name
		$short_list = preg_replace("/$l_appended_domain/",'',$short_list_full);

		//Start the row for this list
		echo  "<tr><td><b>$short_list</b></td><td><b>$short_description</b></td><td>";

		$findmemberurl= $l_admin_url . "/" . $short_list_full . "/members?findmember=" . $l_email . "&setmemberopts_btn&adminpw=" . "$l_adminpw";

		$findmbr=@file_get_contents("$findmemberurl","FALSE");
		// Convert all content to urlencode, to match both new and old mailman style (look also for $le_email)
		$findmbr=urlencode($findmbr);
		if ( $l_debug == 1 ) {
			print "<pre>$findmbr</pre>";
		}

 	if ( $l_debug == 1 ) {
			$scrubbed_findmemberurl = preg_replace("/$l_adminpw/","YOURADMINPW","$findmemberurl") ;
			$my_content = "Using this command:\n" . $scrubbed_findmemberurl . "\nI saw this:\n" . $findmbr ;
			$subject = "Find member in $short_list_full" ;
			mail($l_email, $subject, $my_content, "From:$l_sender");
		}

		/* The line we're looking for looks like the first or the second kind:
		 * Old style mailman
		 * <td><center><INPUT name="curtis@backupcentral.com_digest" type="CHECKBOX" value="on" CHECKED ></center></td>
		 * New style mailman
		 * <td><center><INPUT name="curtis%40backupcentral.com_digest" type="CHECKBOX" value="on" CHECKED ></center></td>
		 * since we urlencoded everything, only %40 will be found.  
		 */
		
		// This line is always found in a subscribed user.
		// maybe we can see with a 'value="off"', but there is.
		// $le_email is in encoded way
		$shortdigestline=urlencode('INPUT name="' . $le_email . '_digest"');
		// We have to quote the match, otherwise characters "\ + * ? [ ^ ] $ ( ) { } = ! < > | :" will gave some sort of error.
		$shortdigestlinequoted=preg_quote($shortdigestline);
		if ( $l_debug == 1 ) {
			print "<pre>$shortdigestline</pre>";
		}

		//If the user is subscribed to this list
		if ( preg_match("/$shortdigestlinequoted/", "$findmbr") ) {

			//If they're in digest format this should match
			$longdigestline=urlencode('INPUT name="' . $le_email . '_digest" type="CHECKBOX" value="on"');
			// We have to quote the match, otherwise characters "\ + * ? [ ^ ] $ ( ) { } = ! < > | :" will gave some sort of error.
			$longdigestlinequoted=preg_quote($longdigestline);
			if ( $l_debug == 1 ) {
				print "<pre>$longdigestline</pre>";
			}

		 	if ( preg_match("/$longdigestlinequoted/", "$findmbr") ) {

				//Print the row that shows them subscribed  in regular format
				echo "<input type='radio' name='radios$radio_counter' value='3'>"._MM_HOSTED_LIST_SUBSCRIBE_NO."</input><br>";
				echo "<input type='radio' name='radios$radio_counter' value='0'>"._MM_HOSTED_LIST_SUBSCRIBE."</input><br>";
				echo "<input type='radio' name='radios$radio_counter' value='1' CHECKED >"._MM_HOSTED_LIST_SUBSCRIBE_DIGEST."</input>";
			} else {

				//If they're subscribed, but not in digest format, it must be
				//regular format
				echo "<input type='radio' name='radios$radio_counter' value='3'>"._MM_HOSTED_LIST_SUBSCRIBE_NO."</input><br>";
				echo "<input type='radio' name='radios$radio_counter' value='0' CHECKED >"._MM_HOSTED_LIST_SUBSCRIBE."</input><br>";
				echo "<input type='radio' name='radios$radio_counter' value='1'>"._MM_HOSTED_LIST_SUBSCRIBE_DIGEST."</input>";

			}

		} else {

			//They're not subscribed.  Print the line that shows them not sub'd
			echo "<input type='radio' name='radios$radio_counter' value='3' CHECKED>"._MM_HOSTED_LIST_SUBSCRIBE_NO."</input><br>";
			echo "<input type='radio' name='radios$radio_counter' value='0'>"._MM_HOSTED_LIST_SUBSCRIBE."</input><br>";
			echo "<input type='radio' name='radios$radio_counter' value='1'>"._MM_HOSTED_LIST_SUBSCRIBE_DIGEST."</input>";
		}

	//Create the input button name
	echo "<input type='hidden' name='list_name$radio_counter' value='$short_list'></input>";
	$radio_counter++;
	//Close out the row
	echo "</td></tr>";

	}
 //End for each list

	//Close out the table
	echo "</table>";

		//Close out the form
		echo "<input type='hidden' name='radio_counter' value='$radio_counter'></input>";
		echo "<input type='hidden' name='nextstep' value='subscribe'></input>";
		echo "<br>";
		echo "<input type='submit' name='submit' value='"._MM_HOSTED_LIST_SUBSCRIBE_BUTTON."'></input><br>";
		echo "</form>";
}
//End function show_initial_page


//This function will actually process the subscription requests
function  process_requests($l_email,$l_fulluserinformation,$l_maildomain,$l_appended_domain,$l_sitename,$l_admin_url,$l_adminpw,$l_sender,$l_debug) {

	$adminurl=$l_admin_url;
	//print "adminurl: $adminurl";
	$content=@file_get_contents("$adminurl","FALSE");

	//Content is now some HTML code containing only a few lines of what we need
	$listarray = preg_split('/\n/',$content);

	//let's loop through it and look for lines that look like this:
	//<td><a href="http://<domain>/mailman/admin/LISTNAME"><strong>
	//<td>Description Text Goes Here</td>

	foreach ($listarray as $element) {

		if ( preg_match("/a href=.*strong.*strong/", "$element") ) { $table="on"; }

		if ( "$table" == "on" ) {
			if ( preg_match("/a href=.*strong.*strong/", "$element") ) {
				$listname = preg_replace("/.*href=./","","$element") ;
				$listname = preg_replace("/.>.*/","","$listname") ;
				$listname = preg_replace("/.*\//","","$listname") ;
				$lists["$listname"] = "on";
			}
		}

		if ( preg_match("/<.table>/", "$element") ) { $table="off";}
	}

	//First we unsub them from all lists. Then we'll sub them to any lists
	//they want to be sub'd to.

	foreach ($lists as $list_name => $short_description) {

		$unsuburl = $l_admin_url . "/" . $list_name . "/members/remove?send_unsub_ack_to_this_batch=0&send_unsub_notifications_to_list_owner=0&unsubscribees_upload=" . $l_email . "&adminpw=" . $l_adminpw;
		
		// we have had timeout issue, let's check this
		ini_set('default_socket_timeout',    120);
		$content=@file_get_contents("$unsuburl","FALSE");
		if($content==false) print "ERROR: unsubscribing from: $list_name";

 		if ( $l_debug == 1 ) {
			$scrubbed_unsuburl = preg_replace("/$l_adminpw/","YOURADMINPW","$unsuburl") ;
			$my_content = "Using this command:\n" . $scrubbed_unsuburl . "\nI saw this:\n" . $content ;
			$subject = "First unsub from $list_name";
			mail($l_email, $subject, $my_content, "From:$l_sender");
		}
	}

	//How many do we have?
	$radio_counter = $_POST['radio_counter'];

	//As long as we have more lists to do...
	for ($x = 0; $x < $radio_counter; $x++) {
		if ( $_POST['radios'.$x] != 3 ) {
			//This function will subscribe them to any lists they should be sub'd to
			//And display the results to the user
			add_to_mailman($l_email,$l_fulluserinformation,$_POST['list_name'.$x]."$l_appended_domain",$_POST['radios'.$x],$l_maildomain,$l_appended_domain,$l_admin_url,$l_adminpw,$l_sender,$l_debug);
		}
	}

	echo "<b>"._MM_PROCESSED_SUBSCRIBE_TEXT5."</b><br>";

	//Grab the email message that got built in the add_to_mailman function
	global $email_message;

	//Add the final line to it
	$email_message = $email_message . _MM_PROCESSED_SUBSCRIBE_TEXT5."\n\n";

	//Send them a single email telling them what happened
	send_email($email_message,$l_email,$l_sitename,$l_sender);

	//Tell php to go back to the front page
	echo "<form action='index.php?option=com_mailman2' method='post'>";
	echo "<br><input type='submit' name='continue' value='"._MM_PROCESSED_RESULT_CONTINUE."'></input><br>";
	echo "</form>";
}

function add_to_mailman($email,$ll_fulluserinformation,$list_name,$digest_option,$ll_maildomain,$ll_appended_domain,$ll_admin_url,$ll_adminpw,$ll_sender,$ll_debug) {

	/*
	 * This work like: 
	 * 1) add user in normal mode
	 * 2) if digest, then turn on (but already subscribed)
	 */
	
	// This is new form: <td><center><INPUT name="webmaster%40agescirimini.it_digest" type="CHECKBOX" value="off" ></center></td>
	$le_email = urlencode($email);
	
 	if ( $ll_debug == 1 ) {
		$my_content = "Here are the variables add_to_mailman was given: email=$email,list=$list_name,dig=$digest_option,append=$ll_appended_domain,adminurl=$ll_admin_url";
		$subject = "Add_to_mailman variables" ;
		mail($email, $subject, $my_content, "From:$ll_sender") ;
	}

	//digest_option == 0, no digest
	//digest_option == 1, digest on

	//Define a global variable that will get passed back to the passing script
	global $email_message;
	
	$ll_fulluserinformation_url = urlencode($ll_fulluserinformation);
	
	$subscribeurl= $ll_admin_url . "/" . $list_name . "/members/add?subscribe_or_invite=0&send_welcome_msg_to_this_batch=0&notification_to_list_owner=0&subscribees_upload=" . $ll_fulluserinformation_url . "&adminpw=" . $ll_adminpw ;
	$content=@file_get_contents("$subscribeurl","FALSE");

 	if ( $ll_debug == 1 ) {
		$scrubbed_subscribeurl = preg_replace("/$ll_adminpw/","YOURADMINPW","$subscribeurl") ;
		$my_content = "Using this command:\n" . $scrubbed_subscribeurl . "\nI saw this:\n" . $content ;
		$subject = "Subscribe to $list_name" ;
		mail($email, $subject, $my_content, "From:$ll_sender") ;
	}

	$short_list = preg_replace("/$ll_appended_domain/",'',$list_name);

	if ($digest_option == 0) {
		//non digest format

		echo "$email"._MM_PROCESSED_SUBSCRIBE_TEXT1."<b>$short_list</b> "._MM_PROCESSED_SUBSCRIBE_TEXT3."<br>";
		echo _MM_PROCESSED_SUBSCRIBE_TEXT4."<A HREF=\"mailto: $short_list@$ll_maildomain\">$short_list@$ll_maildomain</A><br><br>";

		$email_message = $email_message . $email ._MM_PROCESSED_SUBSCRIBE_TEXT1. $short_list ._MM_PROCESSED_SUBSCRIBE_TEXT6."\n";
		$email_message = $email_message . _MM_PROCESSED_SUBSCRIBE_TEXT4;
		$email_message = $email_message . $short_list;
		$email_message = $email_message . "@$ll_maildomain\n\n";

	} elseif ($digest_option == 1) {

		//digest format

		// switch to POST
		$url = null;
		$url = $ll_admin_url . "/" . $list_name . "/members";
		
		$post = null;
		$post["findmember"] = $email;
		$post["adminpw"] = $ll_adminpw;
		$get_actual_config = curl_post($url, $post);
		if($get_actual_config == FALSE) return 0;
		
		// get all fields with email in old format
		preg_match_all("/\<.*" . $email . ".*\>/", $get_actual_config, &$matched[]);
		// get all fields with email in new format
		preg_match_all("/\<.*" . $le_email . ".*\>/", $get_actual_config, &$matched[]);
		// get field for submit
		preg_match("/<.*setmemberopts_btn.*\>/", $get_actual_config, &$matched[]);
		// get field for allmodbit_val
		preg_match("/<.*allmodbit_val.*CHECKED.*\>/", $get_actual_config, &$matched[]);
		
		$existing_values = extract_form($matched);
		$post = array_merge($post, $existing_values);
		
		foreach($post as $key=>$value) {
			if(preg_match("/_digest/", $key)) $post[$key] = "on";
			if($post[$key] == "off") unset($post[$key]);
		}
		
		// debug
		//$post["webmaster%40agescirimini.it_language"] = "it";
		//unset($post["webmaster%40agescirimini.it_unsub"]);
		//$post["webmaster%40agescirimini.it_realname"] = "daniele";
		
		//print "<pre>"; print_r($post); print "</pre>";
			
		$turnondigest = curl_post($url, $post);
		
		$urlv=null;
		foreach($post as $key=>$value) { if($urlv==null) $urlv="?"; else $urlv.="&"; $urlv .= urlencode($key) . "=" . urlencode($value); } 
		$turnondigesturl = $url . $urlv;

 	if ( $ll_debug == 1 ) {
			$scrubbed_turnondigesturl = preg_replace("/$ll_adminpw/","YOURADMINPW","$turnondigesturl") ;
			$my_content = "Using this command:\n" . $scrubbed_turnondigesturl . "\nI saw this:\n" . $turnondigest ;
			$subject = "Set digest for $list_name" ;
			mail($email, $subject, $my_content, "From:$ll_sender") ;
		}
		echo "$email"._MM_PROCESSED_SUBSCRIBE_TEXT1."<b>$short_list</b> "._MM_PROCESSED_SUBSCRIBE_TEXT2."<br>";
		echo _MM_PROCESSED_SUBSCRIBE_TEXT4."<A HREF=\"mailto: $short_list@$ll_maildomain\">$short_list@$ll_maildomain</A><br><br>";

		$email_message = $email_message . $email ._MM_PROCESSED_SUBSCRIBE_TEXT1. $short_list ._MM_PROCESSED_SUBSCRIBE_TEXT6. _MM_PROCESSED_SUBSCRIBE_TEXT2."\n";
		$email_message = $email_message . _MM_PROCESSED_SUBSCRIBE_TEXT4;
		$email_message = $email_message . $short_list;
		$email_message = $email_message . "@$ll_maildomain\n\n";

	}

}

function send_email($message,$email,$ll_sitename,$l_sender)
{
	$subject = $ll_sitename ._MM_EMAIL_SUBJECT;
	mail($email, $subject, $message, "From:$l_sender");
}
?>
